package com.ds.app.database;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import com.ds.app.AppCacheManager;
import com.ds.app.DeskTopPropertyNotFoundException;
import com.ds.common.JDSException;
import com.ds.common.cache.CacheSizes;
import com.ds.common.cache.Cacheable;
import com.ds.common.database.DBAgent;
import com.ds.common.database.DBBeanBase;
import com.ds.common.logging.Log;
import com.ds.common.logging.LogFactory;
import com.ds.org.PersonNotFoundException;
import com.ds.org.conf.OrgConfig;
import com.ds.org.conf.OrgConstants;
import com.ds.org.conf.Query;
import com.ds.org.conf.Query.ColumnMapping;
import com.ds.org.conf.Query.SqlClause;
import com.ds.server.eumus.ConfigCode;


public class DbDeskTopProperty implements Cacheable, Serializable {

    protected static Log log =
            LogFactory.getLog(OrgConstants.CONFIG_KEY.getType(),
                    DbDeskTopProperty.class);
    public static final String DELETE = "DELETE", UPDATE = "UPDATE", NORMAL = "NORMAL", PUBLIC = "public";
    private String status = NORMAL;
    private String personId;
    private ConfigCode configCode;
    private String backGroundColor;
    private String fontColor;
    private String wallPaperId;
    private String shortcut = "[]";
    private String macshortcut = "[]";
    private String macbar = "[]";
    private String quickStart = "[]";
    private String rightbar = "[\"jame\",\"mainpanel\"]";
    private String wallPaperPosition;


    private String themeId;
    private String autorun = "[]";
    private String widget = "[]";
    private String openerwin;


    private OrgConfig getConfig() {
        OrgConfig config = OrgConfig.getInstance(this.configCode);
        return config;
    }

    public DbDeskTopProperty() {
    }

    public DbDeskTopProperty(ConfigCode configCode) {
        if (configCode == null) {
            configCode = OrgConstants.CONFIG_KEY;
        }

        this.configCode = configCode;
    }

    public DbDeskTopProperty(String personId, ConfigCode configCode) throws DeskTopPropertyNotFoundException {

        if (personId == null || personId.equals("")) {
            throw new DeskTopPropertyNotFoundException();
        }
        if (configCode == null) {
            configCode = OrgConstants.CONFIG_KEY;
        }

        this.personId = personId;
        this.configCode = configCode;
        loadFromDb();
    }

    private void loadFromDb() throws DeskTopPropertyNotFoundException {
        DBAgent db = null;
        try {
            db = new DBAgent(this.configCode.getType());

            loadBasic(db);
        } catch (Exception e) {
            throw new DeskTopPropertyNotFoundException("DbDeskTopProperty " + personId + " not found.");
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    public void update() {
        this.status = UPDATE;
    }


    public void commit(Connection cc) throws PersonNotFoundException {
        if (status.equals(NORMAL)) {
            return;
        }
        Connection innerc = null;
        if (cc == null) {
            DBBeanBase db = new DBBeanBase(this.configCode.getType());
            innerc = db.getConn();
        } else {
            innerc = cc;
        }

        try {
            innerc.setAutoCommit(false);
            this.deleteDeskTopProperty(innerc);
            if (!status.equals(DELETE)) {
                this.insertDeskTopProperty(innerc);
            }
            if (cc == null) {
                innerc.commit();
                innerc.close();
            }
            this.status = this.NORMAL;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                innerc.rollback();
                innerc.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        AppCacheManager cacheManager = AppCacheManager.getInstance(configCode);
        cacheManager.getDeskTopPropertyCache().put(this.personId, this);
    }


    private void loadBasic(DBAgent db) throws Exception {

        ResultSet rs = null;
        Query query = null;
        SqlClause sqlClause = null;
        Map columnMap = null;
        String strSql = null;

//		 1.基本信息
        query = getConfig().getQuery("DeskTopProperty");
        if (query == null) {
            log.error("The DeskTopProperty-query-sql is null, please specify it!");
            throw new DeskTopPropertyNotFoundException();
        }
        sqlClause = query.getSqlClause("basic");
        if (sqlClause == null) {
            log.error("The DeskTopProperty-query-sql is null, please specify it!");
            throw new DeskTopPropertyNotFoundException();
        }
        columnMap = sqlClause.getColumnMappings();

        strSql = buildSql(sqlClause);
        if (db.execute(strSql) == 1) {
            rs = db.getQueryResult();
            if (rs.next()) {
                personId =
                        getString(rs, columnMap.get("personId"));
                backGroundColor =
                        getString(rs, columnMap.get("backGroundColor"));

                if (columnMap.get("macshortcut") != null && !columnMap.get("macshortcut").equals("")) {
                    macshortcut =
                            getString(rs, columnMap.get("macshortcut"));
                }
                if (columnMap.get("macbar") != null && !columnMap.get("macbar").equals("")) {
                    macbar =
                            getString(rs, columnMap.get("macbar"));
                }

                fontColor =
                        getString(rs, columnMap.get("fontColor"));
                themeId =
                        getString(rs, columnMap.get("themeId"));
                wallPaperId =
                        getString(rs, columnMap.get("wallPaperId"));
                shortcut =
                        getString(rs, columnMap.get("shortcut"));
                autorun =
                        getString(rs, columnMap.get("autorun"));
                widget =
                        getString(rs, columnMap.get("widget"));
                quickStart =
                        getString(rs, columnMap.get("quickStart"));
                openerwin =
                        getString(rs, columnMap.get("openerwin"));
                if (columnMap.get("rightbar") != null && !columnMap.get("rightbar").equals("")) {
                    rightbar =
                            getString(rs, columnMap.get("rightbar"));
                }

                wallPaperPosition =
                        getString(rs, columnMap.get("wallPaperPosition"));


            }

        }
    }

    public int getCachedSize() {
        int size = 0;
        size += CacheSizes.sizeOfString(backGroundColor);
        size += CacheSizes.sizeOfString(personId);
        size += CacheSizes.sizeOfObject(fontColor);
        size += CacheSizes.sizeOfObject(themeId);
        size += CacheSizes.sizeOfObject(wallPaperId);
        size += CacheSizes.sizeOfObject(shortcut);
        size += CacheSizes.sizeOfObject(macshortcut);
        size += CacheSizes.sizeOfObject(macbar);
        size += CacheSizes.sizeOfObject(autorun);
        size += CacheSizes.sizeOfObject(widget);
        size += CacheSizes.sizeOfObject(quickStart);
        size += CacheSizes.sizeOfObject(openerwin);
        size += CacheSizes.sizeOfObject(rightbar);
        size += CacheSizes.sizeOfObject(wallPaperPosition);

        return size;
    }

    public String getPersonId() {
        return personId;
    }

    public void setPersonId(String personId) {
        this.personId = personId;
    }


    private String buildSql(SqlClause sqlClause) {
        Map columnMap = sqlClause.getColumnMappings();
        String strSql = sqlClause.getMainClause();
        String strWhere = sqlClause.getWhereClause();
        if (strWhere != null && !strWhere.equals("")) {
            strSql = strSql + " " + strWhere + " AND "
                    + ((ColumnMapping) columnMap.get("personId")).getColumn()
                    + "='" + this.personId + "'";
        } else {
            strSql = strSql + " WHERE "
                    + ((ColumnMapping) columnMap.get("personId")).getColumn()
                    + "='" + this.personId + "'";
        }
        return strSql;
    }


    public void deleteDeskTopProperty(Connection c) throws SQLException {
        Query query = getConfig().getQuery("DeskTopProperty");
        SqlClause sqlClause = query.getSqlClause("basic");
        Map columnMap = sqlClause.getColumnMappings();
        PreparedStatement ps = null;
        StringBuffer _sql = new StringBuffer(sqlClause.getDeleteClause() + " where ");
        _sql.append(columnMap.get("personId")).append("='" + this.personId + "'");
        ps = c.prepareStatement(_sql.toString());
        int deletCount = ps.executeUpdate();
        ps.close();
    }

    public void insertDeskTopProperty(Connection c) throws SQLException {
        Query query = getConfig().getQuery("DeskTopProperty");
        SqlClause sqlClause = query.getSqlClause("basic");
        Map columnMap = sqlClause.getColumnMappings();
        StringBuffer _sql = new StringBuffer(sqlClause.getInsertClause() + "(");
        int _dirtyCount = 0;
        _sql.append(columnMap.get("settingId")).append(",");
        _dirtyCount++;
        _sql.append(columnMap.get("personId")).append(",");
        _dirtyCount++;
        if (columnMap.get("macshortcut") != null && !columnMap.get("macshortcut").equals("")) {
            _sql.append(columnMap.get("macshortcut")).append(",");
            _dirtyCount++;
        }
        if (columnMap.get("macbar") != null && !columnMap.get("macbar").equals("")) {
            _sql.append(columnMap.get("macbar")).append(",");
            _dirtyCount++;
        }
        _sql.append(columnMap.get("fontColor")).append(",");
        _dirtyCount++;
        _sql.append(columnMap.get("backGroundColor")).append(",");
        _dirtyCount++;
        _sql.append(columnMap.get("wallPaperId")).append(",");
        _dirtyCount++;
        _sql.append(columnMap.get("shortcut")).append(",");
        _dirtyCount++;
        _sql.append(columnMap.get("themeId")).append(",");
        _dirtyCount++;
        _sql.append(columnMap.get("autorun")).append(",");
        _dirtyCount++;
        _sql.append(columnMap.get("widget")).append(",");
        _dirtyCount++;
        _sql.append(columnMap.get("quickStart")).append(",");
        _dirtyCount++;
        if (columnMap.get("rightbar") != null && !columnMap.get("rightbar").equals("")) {
            _sql.append(columnMap.get("rightbar")).append(",");
            _dirtyCount++;
        }
        _sql.append(columnMap.get("openerwin")).append(",");
        _dirtyCount++;
        _sql.append(columnMap.get("wallPaperPosition")).append(",");
        _dirtyCount++;

        _sql.setLength(_sql.length() - 1);
        _sql.append(") values (");
        for (int i = 0; i < _dirtyCount; i++)
            _sql.append("?,");
        _sql.setLength(_sql.length() - 1);
        _sql.append(")");
        PreparedStatement ps = c.prepareStatement(_sql.toString(),
                ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        _dirtyCount = 0;
        ps.setString(++_dirtyCount, java.util.UUID.randomUUID().toString());
        ps.setString(++_dirtyCount, this.getPersonId());

        if (columnMap.get("macbar") != null && !columnMap.get("macbar").equals("")) {
            ps.setString(++_dirtyCount, this.getMacbar());
        }
        if (columnMap.get("macshortcut") != null && !columnMap.get("macshortcut").equals("")) {
            ps.setString(++_dirtyCount, this.getMacshortcut());
        }
        ps.setString(++_dirtyCount, this.getFontColor());
        ps.setString(++_dirtyCount, this.getBackGroundColor());
        ps.setString(++_dirtyCount, this.getWallPaperId());
        ps.setString(++_dirtyCount, this.getShortcut());
        ps.setString(++_dirtyCount, this.getThemeId());
        ps.setString(++_dirtyCount, this.getAutorun());
        ps.setString(++_dirtyCount, this.getWidget());
        ps.setString(++_dirtyCount, this.getQuickStart());
        if (columnMap.get("rightbar") != null && !columnMap.get("rightbar").equals("")) {
            ps.setString(++_dirtyCount, this.getRightbar());
        }
        ps.setString(++_dirtyCount, this.getOpenerwin());
        ps.setString(++_dirtyCount, this.getWallPaperPosition());
        ps.executeUpdate();
        ps.close();
    }


    private String getString(ResultSet rs, Object column) {
        if (column != null && !column.toString().equals("")) {
            try {
                return rs.getString(((ColumnMapping) column).getColumnAlias());
            } catch (SQLException ex) {
                return null;
            }
        }
        return null;
    }


    public String getBackGroundColor() {
        return backGroundColor;
    }


    public void setBackGroundColor(String backGroundColor) {
        this.backGroundColor = backGroundColor;
    }


    public String getFontColor() {
        return fontColor;
    }


    public void setFontColor(String fontColor) {
        this.fontColor = fontColor;
    }


    public String getShortcut() {
        return shortcut;
    }


    public void setShortcut(String shortcut) {
        this.shortcut = shortcut;
    }


    public String getThemeId() {
        return themeId;
    }


    public void setThemeId(String themeId) {
        this.themeId = themeId;
    }


    public String getWallPaperId() {
        return wallPaperId;
    }


    public void setWallPaperId(String wallPaperId) {
        this.wallPaperId = wallPaperId;
    }


    public String getAutorun() {
        return autorun;
    }

    public String getWidget() {
        return widget;
    }

    public void setAutorun(String autorun) {
        this.autorun = autorun;
    }

    public void setWidget(String widget) {
        this.widget = widget;
    }

    public String getQuickStart() {
        return quickStart;
    }

    public void setQuickStart(String quickStart) {
        this.quickStart = quickStart;
    }

    public String getOpenerwin() {
        return openerwin;
    }

    public void setOpenerwin(String openerwin) {
        this.openerwin = openerwin;
    }

    public String getWallPaperPosition() {
        return wallPaperPosition;
    }

    public void setWallPaperPosition(String wallPaperPosition) {
        this.wallPaperPosition = wallPaperPosition;
    }

    public String getRightbar() {
        return rightbar;
    }

    public void setRightbar(String rightbar) {
        this.rightbar = rightbar;
    }

    public String getMacbar() {
        return macbar;
    }

    public void setMacbar(String macbar) {
        this.macbar = macbar;
    }

    public String getMacshortcut() {
        return macshortcut;
    }

    public void setMacshortcut(String macshortcut) {
        this.macshortcut = macshortcut;
    }


}
